<?php

defined("_JEXEC") or die("Restricted access");

jimport("joomla.application.conponent.model");
//hello model
Class cauhoiModelcauhoi extends JModel
{
    
    //lay du lieu o bang chudecon
    public function laychude()
    {
        $db = JFactory::getDbo();
        $query = 'select * from #__chudecon';
        $db->setQuery($query);
	//return $db;
        $kq = $db->loadObjectList();
	return $kq;
    }
    
    //ham them vao csdl cho nganhangcauhoi
    public function them($noidung,$listdapan,$chude,$datthieu,$datda)
    {
        
        //ket noi
        $db = JFactory::getDbo();
        //dem macahoi trong bang nganhangcauhoi
        $query1="select max(macauhoinh) from #__nganhangcauhoi";
        $db->setQuery($query1);
        $demch = $db->loadResult();
        //print_r($demch);
       
        $mach = $demch+1;
        //print_r($mach);
        /* them cauhoi */       
        $qthemch = "insert into #__nganhangcauhoi(macauhoinh,noidung) values('$mach','$noidung')";
         $db->setQuery($qthemch);
         $db->query();//luu y cho insert, delete,update..
         //dem macauhoi vao bang cauhoi
        $qdemch1="select max(macauhoi) as dem from #__cauhoi";
        $db->setQuery($qdemch1);
        $demch1 = $db->loadResult();
        //print_r($demch1);
        //them vao bang cauhoi
        $mach1 = $demch1 +1;
        $qthemch1 = "insert into #__cauhoi(macauhoi,macauhoinh,machudecon) values('$mach1','$mach',$chude)";
        $db->setQuery($qthemch1);
        $db->query();
    //print_r($kq);
        //kiem tra dapan      
        if($listdapan!="")
        {   
            //them khoa cho madapan
            $querydemda="select max(madapan) as dem from #__dapan";
            $db->setQuery($querydemda);
            $demda = $db->loadResult();
            $mada = $demda+1;
            
            //them dapan vao csdl                        
            foreach ($listdapan as $dapan)
            {
                //them dap an vao bang
               $queryda = "insert into #__dapan(madapan,cauhoi_id,noidung) values('$mada','$mach','$dapan')";
               $db->setQuery($queryda);
               $db->query();
               $mada++;              
            }
            //them hinh thuc tra loi
            $qhthuc = "insert into #__quidinhtraloi(macauhoi,sodatoithieu,sodatoida) values('$mach','$datthieu','$datda')";
            $db->setQuery($qhthuc);
            $db->query();
        }
        return TRUE;
    }   
    
    //kiem tra noidung cau hoi
    public function kiemtra($noidung)
    {
        $db = JFactory::getDbo();
        $qkt = "select macauhoinh from #__nganhangcauhoi where noidung='$noidung'";
        $db->setQuery($qkt);
        $kqkt = $db->loadResult();
        if($kqkt==NULL)
        {
            return TRUE;
        }
        return FALSE;
    }
}
?>
